const config = require('./config.js')
var baseUrl = config.websocketServer; // websocket服务器baseUrl
// socket已经连接成功
var sotk = null;
// socket已经调用打开标志
let socketOpen = false;
// 判断心跳变量
var heart = ''
// 心跳失败次数
var heartBeatFailCount = 0
// 终止心跳
var heartBeatTimeOut = null;
// 终止重新连接
var connectSocketTimeOut = null;
var loginName = '';

function connect(username) {
  if (username != '') {
    loginName = username
  }
  sotk = wx.connectSocket({
    url: baseUrl + loginName,
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {},
    fail: function (e) {
      wx.showToast({
        title: "后台服务已停用",
        icon: 'none',
        duration: 1000
      });
    },
  })

  sotk.onOpen(res => {
    socketOpen = true;
    console.log('服务器 WebSocket 连接已开启');
    startHeartBeat()
  })
  sotk.onClose(onClose => {
    socketOpen = false;
    console.log('监听 WebSocket 连接关闭事件。', onClose)
    stopHeartBeat()
  })
  sotk.onError(onError => {
    socketOpen = true;
    if (connectSocketTimeOut) {
      clearTimeout(connectSocketTimeOut);
      connectSocketTimeOut = null;
    }
    console.log('监听 WebSocket 错误。错误信息', onError)
  })

  return sotk
}

function sendSocketMessage(options) {
  if (socketOpen) {
    sotk.send({
      data: options.msg,
      success: function (res) {
        if (options) {
          options.success && options.success(res);
        }
      },
      fail: function (res) {
        if (options) {
          options.fail && options.fail(res);
        }
      }
    })
  }
}
// 开始心跳
function startHeartBeat() {
  console.log('socket开始心跳')
  heart = 'heart';
  heartBeat();
}

// 结束心跳
function stopHeartBeat() {
  console.log('socket结束心跳')
  heart = '';
  if (heartBeatTimeOut) {
    clearTimeout(heartBeatTimeOut);
    heartBeatTimeOut = null;
  }
  if (connectSocketTimeOut) {
    clearTimeout(connectSocketTimeOut);
    connectSocketTimeOut = null;
  }
}
// 心跳
function heartBeat() {
  if (!socketOpen) {
    return;
  }
  sendSocketMessage({
    msg: JSON.stringify({
      'heartUser': loginName,
      'msg_type': 'heart'
    }),
    success: function (res) {
      console.log('socket心跳成功');
      if (socketOpen) {
        heartBeatTimeOut = setTimeout(() => {
          heartBeat();
        }, 20000);
      }
    },
    fail: function (res) {
      console.log('socket心跳失败');
      if (heartBeatFailCount > 2) {
        // 重连
        connect(loginName);
      }
      if (heart) {
        heartBeatTimeOut = setTimeout(() => {
          heartBeat();
        }, 7000);
      }
      heartBeatFailCount++;
    },
  });
}
// 监听WebSocket关闭。
wx.onSocketClose(function (res) {
  console.log('WebSocket 已关闭！')
  // if (socketOpen) {
  //   clearTimeout(connectSocketTimeOut)
  //   connectSocketTimeOut = setTimeout(() => {
  //     connect(loginName);
  //   }, 3000);
  // }
})
module.exports.connect = connect;